//
//  AmbitusListViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "AmbitusListViewController.h"
#import "AmbitusTableViewController.h"
#import "AmbitusListModel.h"
#import "AmbitusListCell.h"
#import "AmbitusDetailViewController.h"

@interface AmbitusListViewController ()<AmbitusTableViewControllerDelegate>
@property (nonatomic, strong) NSMutableArray *AmbitusListArray;
@property (nonatomic, strong) UILabel *cityLable;

@end

@implementation AmbitusListViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    self.edgesForExtendedLayout = UIRectEdgeNone;
  
    //[self setUpData];
    self.view.backgroundColor = [UIColor whiteColor];
    [self setNavigationBar];
    [self freshHeader];
    [self addInternetObserver];
}

- (void)freshHeader
{
    if ([_app internetReachableOrNot]) {
        self.tableView.header = [LYBAnimationHeader headerWithRefreshingTarget:self refreshingAction:@selector(setUpData)];
        [self.tableView.header beginRefreshing];
    } else {
        [self alertController];
    }
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}


- (void)setNavigationBar
{
    self.navigationItem.title = @"户外";
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(0, 0, 50, 30);
    [button addTarget:self action:@selector(actionRightButton:) forControlEvents:UIControlEventTouchUpInside];
    
    self.cityLable = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 30, 30)];
    self.cityLable.text = @"北京";
    self.cityLable.font = [UIFont systemFontOfSize:13];
    [button addSubview:self.cityLable];
    
    UIImageView *imageV = [[UIImageView alloc] initWithFrame:CGRectMake(self.cityLable.right, 5, 20, 20)];
    imageV.image = [[UIImage imageNamed:@"TestCity.png"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
    imageV.tintColor = [UIColor whiteColor];
    
    [button addSubview:imageV];
    
    //    [button setTitle:@"三亚" forState:(UIControlStateNormal)];
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithCustomView:button];
     self.navigationItem.rightBarButtonItem = rightButton;


    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
 
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
      
    if (self.city_id == 0) {
        self.city_id = 53;
    }
 self.urlString = [NSString stringWithFormat:@"http://api.lanrenzhoumo.com/wh/common/leos?v=2&session_id=00004016b3e14bbea40c1aa1a14c2273a35352&lon=116.343596&page=1&category=hwyd&lat=40.030671&city_id=%ld",self.city_id];
    NSString *url = [self.urlString stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url] cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:config];
    self.AmbitusListArray = [NSMutableArray array];
    NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            NSLog(@"Httperror: %@%ld", error.localizedDescription, error.code);
        } else {
            NSDictionary *tempDict = [NSJSONSerialization JSONObjectWithData:data options:(NSJSONReadingMutableContainers) error:nil];
            NSMutableArray *tempArray = [tempDict valueForKey:@"result"];
            for (NSDictionary *dic in tempArray) {
                AmbitusListModel *model = [[AmbitusListModel alloc] init];
                [model setValuesForKeysWithDictionary:dic];
                NSMutableArray *imageArray = dic[@"front_cover_image_list"];
                [model setValue:imageArray[0] forKey:@"imageUrl"];
                [self.AmbitusListArray addObject:model];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                 [self stopLoading];
                [self.tableView.header endRefreshing];
                [self.tableView reloadData];
               
            });
            
        }
    }];
    [dataTask resume];
    } else {
        [self alertController];
    }
}

- (void)alertController
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的当前网络中断或网络信号差, 请检查网络后重新进入!!" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertController addAction:cancelAction];
    [self presentViewController:alertController animated:YES completion:nil];
}

// 加载动画
- (void)addAnimation
{
    _viewV = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 100, kScreenHeight / 2 - 80, 200, 80)];
    _viewV.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    _viewV.layer.cornerRadius = 10;
    _viewV.layer.masksToBounds = YES;
    [self.view addSubview:_viewV];
    self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake(_viewV.width / 2 - 20, _viewV.height / 2 - 20 , 40, 40)];
    [_viewV addSubview:self.indicator];
    [self.indicator startAnimating];
    // [self performSelector:@selector(stopLoading:) withObject:self.indicator afterDelay:5];
}

- (void)stopLoading
{
    [_indicator stopAnimating];
    [self.viewV removeFromSuperview];
}


#pragma mark -- 城市列表的代理方法
- (void)reloadAmbitusListById:(NSInteger)cityId cityName:(NSString *)cityName
{
    self.cityLable.text= cityName;
    self.city_id = cityId;
     [self addAnimation];
    [self setUpData];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.AmbitusListArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *identifier = @"AmbitusList";
    AmbitusListCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier ];
    if (cell == nil) {
        cell = [[AmbitusListCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.AmbitusListArray.count > 0) {
        AmbitusListModel *model = self.AmbitusListArray[indexPath.row];
        cell.model = model;
    }
    
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    AmbitusListModel *model = self.AmbitusListArray[indexPath.row];
    AmbitusDetailViewController *adVC = [[AmbitusDetailViewController alloc] init];
    adVC.imageUrl = model.imageUrl;
    adVC.leo_id = model.leo_id;
    adVC.titleStr = model.title;
    [self.navigationController pushViewController:adVC animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    AmbitusListModel *model = self.AmbitusListArray[indexPath.row];
   CGFloat height = [AmbitusListCell cellHeightWithModel:model];
    return 170 + height + 3;
}

#pragma mark -- button的点击方法
- (void)actionRightButton:(UIBarButtonItem *)rightButton
{
    AmbitusTableViewController *aTVC = [[AmbitusTableViewController alloc] init];
    aTVC.delegate = self;
    [self.navigationController pushViewController:aTVC animated:YES];
    
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
